package com.usf.jprovider.schema.provider.dao.resultset;

import java.util.List;

import javax.xml.bind.annotation.XmlElement;

import com.usf.jprovider.constants.Constants;
import com.usf.jprovider.object.JObjectNode;
import com.usf.jprovider.object.env.Environment;
import com.usf.jprovider.object.type.JType;
import com.usf.jprovider.schema.provider.pointer.AbstractPointer;
import com.usf.jprovider.schema.provider.pointer.dynamic.GlobalPointer;
import com.usf.jprovider.schema.provider.pointer.dynamic.LocalPointer;
import com.usf.jprovider.tools.DAOTools;
import com.usf.jprovider.tools.StringTools;

public final class DAOQuery extends AbstractDAOResultSetSource {
	
	@XmlElement protected String query;
	
	public DAOQuery() {
		super();
		query = "";
	}
	public String getQuery() {
		return query;
	}
	
	@Override
	protected String createUnformated(Environment env, JObjectNode node) throws Exception {
		String query = parse(env, node, this.query);
		query = entrySelector.selectQuery(env, query);
		String values = DAOTools.executeSelectQuery(env.getConnection(), query);
		return valueSelector.create(env, node, values);
	}
	@Override
	public boolean checkValue(Environment env, JObjectNode node,  JType<?> object) throws Exception{
		String query = parse(env, node, this.query);
		String value = valueSelector.toQuery(object.toString());
		query = entrySelector.selectQuery(env, query, value);
		String values = DAOTools.executeSelectQuery(env.getConnection(), query);
		return valueSelector.check(env, node, values, object.toString());
	}
	
	protected String parse(Environment env, JObjectNode node, String query) throws Exception {
		List<String>variables = StringTools.extractVariables(query, Constants.LOCAL_POINTER);
		AbstractPointer pointer;
		for(String value : variables){
			pointer = new LocalPointer(value);
			query = query.replace(Constants.LOCAL_POINTER + value, "'" + pointer.create(env, node) + "'");
		}
		variables = StringTools.extractVariables(query, Constants.GLOBAL_POINTER);
		for(String value : variables){
			pointer = new GlobalPointer(value);
			query = query.replace(Constants.GLOBAL_POINTER + value, "'" + pointer.create(env, node) + "'");
		}
		return query;
	}

	@Override
	public boolean isDependent(JObjectNode node) throws Exception {
		boolean value = false;
		AbstractPointer pointer;
		List<String>variables = StringTools.extractVariables(query, Constants.LOCAL_POINTER);
		for(String variable : variables) {
			pointer = new LocalPointer(variable);
			value = value || pointer.isDependent(node);
		}
		variables = StringTools.extractVariables(query, Constants.GLOBAL_POINTER);
		for(String variable : variables) {
			pointer = new GlobalPointer(variable);
			value = value || pointer.isDependent(node);
		}
		return value;
	}
}
